using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Deepcode.Flux.Core.UI.Controls
{
	/// <summary>
	/// DateTimeValidator is a special validation control that
	/// ensures a textbox (or a DateInput control) contains
	/// a valid date, and optionally, a time. It also has a 
	/// client side validation function.
	/// </summary>
	public class DateInputValidator : Base.BaseValidator
	{
		/// <summary>
		/// Set this to true to allow the validator to state that an empty
		/// field is valid.
		/// </summary>
		public bool AllowNulls
		{
			get
			{
				object o = ViewState["nulls"];
				if( o == null ) return false;
				return (bool) o;
			}
			set
			{
				ViewState["nulls"] = value;
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender (e);
			this.LoadClientScript("DateInput/DateInputValidator.js", 
				"Deepcode.Flux.UI.Controls.DateTimeValidator");
		}

		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			base.AddAttributesToRender (writer);
			if( RenderUplevel )
			{
				writer.AddAttribute( "evaluationfunction", "MCD_ValidateDateTime" );
				writer.AddAttribute( "allownull", AllowNulls.ToString());
			}
		}

		protected override bool EvaluateIsValid()
		{
			try
			{
				// This is the server side validation routine
				if( this.AllowNulls && (GetControlValidationValue(ControlToValidate)=="")) return true;
				System.DateTime dt = System.DateTime.Parse(GetControlValidationValue(ControlToValidate));
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
}